//登录页
var utils = require('../../utils/util.js')
var app = getApp()
Page({
	data: {
    loginError:false,
    isLogin:true,
    openid:'',
    loginData:{
      loginName: '',
      password: ''
    }
	}, 
  onLoad:function(){
     app.globalData.user = null
     app.globalData.cookie = ''
     this.loginCheck()
  },
  bindLoginNameInput: function(e) {
    this.setData({'loginData.loginName': e.detail.value})
	},
	bindPasswordInput: function(e) {
    this.setData({'loginData.password': e.detail.value})
	},

  loginCheck:function(e){
    var that = this;
    wx.login({
      success: function (res){
        var code = res.code
        wx.getSetting({
          success(setRes) {
            // 判断是否已授权  
            if (!setRes.authSetting['scope.userInfo']) {
              // 未授权  
              //调起授权窗口
              wx.authorize({
                scope: 'scope.userInfo',
                success() {
                  //获取用户信息  
                  wx.getUserInfo({
                    lang: "zh_CN",
                    success: function (userRes) {
                      //发起网络请求  
                      that.loginRequest(that, code, userRes.encryptedData, userRes.iv)
                    },
                    fali:function(){
                     that.unAuthorizeAlert(that, code)
                    }
                  })
                },
                fail:function(){
                 that.unAuthorizeAlert(that, code)
                }
              })
            } else {
              //获取用户信息  
              wx.getUserInfo({
                lang: "zh_CN",
                success: function (userRes) {
                  //发起网络请求  
                  that.loginRequest(that, code, userRes.encryptedData, userRes.iv)
                }
              })
            }
          }
        })
      }
    })  
  },

  unAuthorizeAlert: function (self, code){
    wx.showModal({
      title: '警告',
      content: '您点击了拒绝授权,将无法正常使用软件,点击确定重新获取授权',
      success: function (result) {
        if (result.confirm) {
          wx.openSetting({
            success: (resul) => {
              if (resul.authSetting["scope.userInfo"]) {
                wx.showToast({ title: '加载中', icon: 'loading' });
                wx.getUserInfo({
                  lang: "zh_CN",
                  success: function (userRes) {
                    //发起网络请求  
                    self.loginRequest(self, code, userRes.encryptedData, userRes.iv)
                  }
                })
              }else{
                self.unAuthorizeAlert(self, code)
              }
            }
          })

        } else {
          self.unAuthorizeAlert(self, code)
        }
      }
    })
  },

  loginRequest: function (that,code, encryptedData, iv){
    wx.showToast({ title: '加载中', icon: 'loading' });
    console.log("login url " + app.GLOBAL_CONFIG.commonUrl)
    wx.request({
      url: app.GLOBAL_CONFIG.commonUrl + "/project/miniprogram/getUserInfo.do",
      data: {
        code: code,
        encryptedData: encryptedData,
        iv: iv
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success: function (result) {
        if (result.data.errcode != undefined || result.data.errcode != null) {
          console.log("error and code is " + result.data.errcode)
        } else if (result.data.userStatus == "1") {
          let ybdUser = result.data.ybdUserData[0];
          let sessionId = result.data.seesionId;
          sessionId = 'JSESSIONID=' + sessionId;
          app.globalData.user = ybdUser;
          app.globalData.cookie = sessionId;
          wx.setStorageSync('user', ybdUser);
          wx.setStorageSync('cookie', sessionId);
          wx.hideToast();
          wx.switchTab({
            //url: '../index/index',
            url: '../todo/todo',
          })
        } else if (result.data.userStatus == "0") {
          let openId = result.data.openId;
          that.setData({
            openid: openId,
            isLogin: false
          })
          wx.hideToast();
        }
      },
      fail: function (res) {
        console.log("获取用户信息失败 "+res)
      }
    })
  },

	login: function(e) {
    var that = this;
    var thatData = that.data;
    if (!thatData.loginData.loginName ){
      wx.showToast({
        title: '请输入用户名',
        image:'../../images/warning.png',
        duration:2000,
      })
      return;
    } else if (!thatData.loginData.password){
      wx.showToast({
        title: '请输入密码',
        image: '../../images/warning.png',
        duration:2000,
      })
      return;
    }else{
      if (utils.checkNetWorkStatus() == false){
        console.log('网络错误');
        wx.showToast({
          title: '网络错误请检查',
          image:'../../images/fail.png',
          duration:2000
        }) 
      }else{
        wx.showToast({ title: '登录请求中', icon: 'loading'});
        var url = app.GLOBAL_CONFIG.commonUrl + app.GLOBAL_CONFIG.loginUrl + '?loginName=' + thatData.loginData.loginName + '&password=' + thatData.loginData.password + '&openid=' + thatData.openid
        console.log("login url " + url)
        utils.postRequest(url, '',app, that, that.successDeal,function (res) {
            wx.hideToast();
            wx.showModal({
              title: '登录失败', content: '请检查设置是否正确！', showCancel: false, success: function (res) {
                return;
              }
            });
          })
      }
     
    }
	},

  successDeal: function (res, that){
    wx.hideToast();
    var operateMessage = res.data.operateMessage
    if (operateMessage != null && res.data.loginStatus == "fail"){
     that.setData({
       loginError:true,
       errorMsg: operateMessage
       })
    }else{
      var obj = res.data.userData[0],
        sessionId = res.data.seesionId;
      if (obj != null & sessionId != null) {
        app.globalData.user = obj;
        app.globalData.cookie = 'JSESSIONID=' + sessionId;
        wx.setStorageSync('user', obj);
        wx.setStorageSync('cookie', sessionId);
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2];
        if (prevPage == undefined) {
          wx.switchTab({
            //url: '../index/index',
            url: '../todo/todo',
          })
        } else {
          wx.navigateBack({
            delta: 1
          })
        }
      } else {
        wx.hideToast();
        wx.showModal({
          title: '登录失败', content: '请检查您填写的用户信息！', showCancel: false, success: function (res) {
            return;
          }
        });
      }
    }

  }
})
